package com.example.weatheringwithyou.ui.login

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.widget.Toast
import com.example.weatheringwithyou.MainActivity
import com.example.weatheringwithyou.base.BaseBindingActivity
import com.example.weatheringwithyou.bean.LoginRequest
import com.example.weatheringwithyou.databinding.AcLoginBinding
import com.example.weatheringwithyou.utils.RetrofitClient
import androidx.lifecycle.lifecycleScope
import com.example.weatheringwithyou.storage.TokenPreferences
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.coroutines.Dispatchers
class LoginActivity : BaseBindingActivity<AcLoginBinding>() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 设置登录按钮点击事件监听器
        binding.tvLogin.setOnClickListener {
            doLogin()
        }
    }


    override fun initBinding(layoutInflater: LayoutInflater): AcLoginBinding {
        return AcLoginBinding.inflate(layoutInflater)
    }

    fun doLogin() {
        //徐洪俊  3838438  http://192.168.31.39:3000/
        //weiman18 123456 http://192.168.31.45:3000/
        //
        // 1. 获取用户输入的账号和密码
        val username = binding.etUsername.text.toString()
        val password = binding.etPassword.text.toString()

        // 2. 账号或密码为空，显示错误提示
        if (username.isEmpty() || password.isEmpty()) {
            Toast.makeText(this, "请填写账号和密码", Toast.LENGTH_SHORT).show()
            return
        }

        // 3. 登录逻辑
        try {
            lifecycleScope.launch withContext@{
                // 创建登录请求对象，传入用户名和密码
                val req = LoginRequest(username, password)
                // 在IO线程中执行网络请求
                val res = withContext(Dispatchers.IO) {
                    RetrofitClient.apiService.login(req)
                }

                // 检查响应码是否为10000（表示成功）
                if (res.code == 10000) {
                    // 从响应中获取token
                    val token = res.data?.token

                    if (token.isNullOrEmpty()) {
                        // 处理token为空的情况
                        Toast.makeText(this@LoginActivity, "登录失败", Toast.LENGTH_SHORT).show()
                        return@withContext
                    }
                    // 持久化存储token
                    TokenPreferences.getInstance(this@LoginActivity).saveToken(token.toString())
                    // 显示登录成功的Toast提示
                    Toast.makeText(this@LoginActivity, "登录成功", Toast.LENGTH_SHORT).show()

                    // 启动MainActivity并结束当前Activity
                    startActivity(Intent(this@LoginActivity, MainActivity::class.java))
                    finish()
                } else {
                    // 处理响应失败的情况
                    Toast.makeText(
                        this@LoginActivity,
                        "登录失败",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }
        } catch (e: Exception){
            Toast.makeText(this, "登录失败", Toast.LENGTH_SHORT).show()
        }
    }
}